package com.hw.one.dam2.dao;

import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.util.AQIComparatorMap;
import com.hw.one.dam2.util.CalendarUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/05/23 17:15.
 *
 * 油烟数据Dao实现类
 */
@Repository(value = "lampBlackDao")
public class LampBlackDao implements ILampBlackDao{

    @Autowired
    private MongoTemplate mongoTemplateStandardSiteData;


    @Override
    public List<Map> findLampBlackNewMinuteDataBySiteCodeList(List<String> siteCodeList) {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DamConstant.NO_SPLIT_SDF_YM);

        String tableTime = sdf.format(calendar.getTime());
        String endTime = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD_HMS);
        calendar.add(Calendar.HOUR, -12);
        String startTime = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD_HMS);
        // 查询条件 增加时间查询条件
        Criteria criteria = Criteria.where("SITECODE").in(siteCodeList).and("MONITORTIME").gte(startTime).lte(endTime);

        // 创建查询对象，根据油烟浓度倒叙排列
        Query query = new Query(criteria).with(new Sort(Sort.Direction.DESC, "CONCENTRATION"));
        List<Map> newDtaList = mongoTemplateStandardSiteData.find(query, Map.class, "T_DATA_SC_MIN_S_COLLECT-" + tableTime);

        AQIComparatorMap comparator = new AQIComparatorMap();

        Collections.sort(newDtaList, comparator);

        return newDtaList;
    }

    @Override
    public List<Map> findLampBlack12HourDataBySiteCode(String siteCode, int address) {

        Calendar calendar = Calendar.getInstance();
        int monthNum = calendar.get(Calendar.MONTH);
        int yearNum = calendar.get(Calendar.YEAR);

        String tableTime = null;
        // 如果是1月到6月，则表名称是年+a
        if(monthNum<=5){
            tableTime = yearNum + "a";
        }else {
            tableTime = yearNum + "b";
        }

        // 查询条件 增加时间查询条件
        Criteria criteria = Criteria.where("SITECODE").is(siteCode);
        // 获取最新记录
        List<Map> newDataList = mongoTemplateStandardSiteData.find(
            new Query(criteria).with(new Sort(Sort.Direction.DESC, "MONITORTIME")).limit(12), Map.class,
            "T_DATA_SC_HOUR_S_COLLECT-" + tableTime);

        Collections.reverse(newDataList);

        return newDataList;
    }


}
